/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
const FULFILLED = 'fulfilled';  // 成功状态
const REJECTED = 'rejected';    // 失败状态
const PENDING = 'pending';      //等待状态

class MyPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    }
    catch (err) {
      reject(err)
    }
  }

  // 状态
  status = PENDING
  // 成功值
  value = undefined
  // 失败原因
  reason = undefined
  // 成功回调
  successCallback = []
  // 失败回调
  failCallback = []

  resolve = value => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = value
    // 判断成功回调是否存在 存在则调用 
    // this.successCallback && this.successCallback(this.value)
    while (this.successCallback.length) this.successCallback.shift()()
  }

  reject = reason => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    // 判断失败回调是否存在 存在则调用 
    // this.failCallback && this.failCallback(this.reason)
    while (this.failCallback.length) this.failCallback.shift()()
  }

  then(successCallback, failCallback) {
    // then参数可选 判断成功回调是否存在 存在就调用 不存在则传递
    successCallback? successCallback:value => value
    // then参数可选 判断失败回调是否存在 存在就调用 不存在抛出
    failCallback? failCallback:reason => {throw reason}
    let promise2 = new MyPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        //异步 
        setTimeout(() => {
          // 捕捉错误
          try {
            let x = successCallback(this.value)
            // resolve(x)
            // 判断 x 的值是否是promise
            // promise 查看返回的结果
            // 普通值直接resolve返回
            resolvePromise(promise2, x, resolve, reject)
          } catch (err) {
            reject(err)
          }
        }, 0);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason)
            // resolve(x)
            resolvePromise(promise2, x, resolve, reject)
          } catch (err) {
            reject(err)
          }
        }, 0);
      } else {
        // 执行异步代码 将异步的成功回调失败回调存储起来
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value)
              // resolve(x)
              resolvePromise(promise2, x, resolve, reject)
            } catch (err) {
              reject(err)
            }
          }, 0);
        })
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason)
              // resolve(x)
              resolvePromise(promise2, x, resolve, reject)
            } catch (err) {
              reject(err)
            }
          }, 0);
        })
      }
      return promise2
    })
  }

  finally (callBack) {
    this.then(value => {
      //可以用then继续调用 返回一个promise
      return MyPromise.resolve(callBack()).then(() => value)
      // callBack()
      // return value
    },reason => {
      //可以用then继续调用 返回一个promise
      return MyPromise.resolve(callBack()).then(() => {throw reason})
      // callBack()
      // throw reason
    })
  }

  catch (failCallback) {
    return this.then(undefined, failCallback)
  }

  static all (array){
    // 存放结果数组
    let results = []
    // index === array 判断异步执行完毕
    let index = 0
    return new MyPromise((resolve, reject) => {
      // 定义将数组项执行结果添加到结果数组
      function addData(key, value) {
        results[key] = value
        index++ 
        if(index === array.length){
          resolve(results)
        }
      }
      for (let i = 0;i < array.length; i++) {
        let current = array[i]
        if (current instanceof MyPromise) {
          // 是promise
          // 成功添加到结果数组 失败停止调用reject
          current.then(value => addData(i,value), reason => reject(reason))
        }else{
          // 是普通值 直接返回添加到结果数组
          addData(i, array[i])
        }
      }
      // resolve(results)
    })
  }

  // 将非promise转换为promise对象
  static resolve (value) {
    // 判断是非promise/promise对象   非promise装换promise对象 promise对象返回
    if (value instanceof MyPromise) return value
    return new MyPromise(resolve => resolve(value)) 
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  // 判断promise是否循环调用
  if (x === promise2) {
    // return new TypeError('promise 循环调用报错')
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  }
  // 判断是否是promise promise返回调用后的值  常数直接返回值
  if (x instanceof MyPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = MyPromise